import os
import warnings
from common.readyaml import ReadYamlData
import pytest
from common.recordlog import logs
from common.removefile import remove_file
import time
from common.dingRobot import send_dd_msg
from conf.setting import dd_msg
from common.Pjenkins import PJenkins



@pytest.fixture(scope="module",autouse=True)
def clean_file():

    # 禁用HTTPS告警，ResourceWarning
    warnings.simplefilter('ignore', ResourceWarning)
    # ReadYamlData().clean_extract_yaml_data()
    # logs.info("已清空extract.yml文件数据")
    remove_file("./allure-results", ['json', 'txt', 'attach', 'properties'])
    logs.info("已清空/allure-results目录中的文件")

# 利用pytest框架得到测试结果
def generate_test_summary(terminalreporter):
    """生成测试结果摘要字符串"""
    logs.info("生成测试结果摘要字符串")
    total = terminalreporter._numcollected
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    error = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    duration = time.time() - terminalreporter._sessionstarttime
    summary = f"""
    csdn_test自动化测试结果，通知如下，请着重关注测试失败的接口，具体执行结果如下：
    测试用例总数：{total}
    测试通过数：{passed}
    测试失败数：{failed}
    错误数量：{error}
    跳过执行数量：{skipped}
    执行总时长：{round(duration,2)}s
    allure测试报告: {PJenkins().get_report_url()}
    """
    print(summary)
    return summary


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """自动收集pytest框架执行的测试结果并打印摘要信息"""
    summary = generate_test_summary(terminalreporter)
    # 利用jenkins中的allure获取测试结果
    # summary = PJenkins().report_success_or_fail()

    if dd_msg:
        logs.info("发送钉钉消息")
        send_dd_msg(summary)



